<template>
  <div class="login">
    <div class="login_form">
      <div class="title">{{ show ? '贵州众创云通科技' : '忘记密码' }}</div>
      <div v-if="show" class="form_box">
        <el-tabs v-model="active" @tab-change="resetForm">
          <el-tab-pane label="手机登录" name="1"></el-tab-pane>
          <el-tab-pane label="账号登录" name="2"></el-tab-pane>
        </el-tabs>
        <el-form class="custom_form" ref="formRef" :model="form" :rules="rules" size="large">
          <el-form-item :prop="active === '1' ? 'phone' : 'username'">
            <el-input v-model="form[active === '1' ? 'phone' : 'username']" type="text" :placeholder="active === '1' ? '请输入手机号' : '请输入账号'" clearable @keyup.enter="doLogin"></el-input>
          </el-form-item>
          <el-form-item v-if="active === '2'" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入密码" clearable @keyup.enter="doLogin"></el-input>
          </el-form-item>
          <el-form-item :prop="active === '1' ? 'smsCode' : 'verifyCode'">
            <div class="code_box">
              <el-input v-model="form[active === '1' ? 'smsCode' : 'verifyCode']" placeholder="验证码" clearable @keyup.enter="doLogin"></el-input>
              <el-button v-if="active === '1'" :disabled="smsCodeDisabled" color="#409EFF" @click="doSendSmsCode">{{smsCodeText}}</el-button>
              <el-image v-else :src="verifyCodeImg" @click="doGetImgCode">
                <template #error>
                  <div class="load-code">正在加载</div>
                </template>
              </el-image>
            </div>
          </el-form-item>
          <el-button class="login_btn" :loading="loading" :disabled="loading" color="#409EFF" @click="doLogin">{{ loading ? '正在登录' : '登录' }}</el-button>
          <div class="other">
            <el-button icon="QuestionFilled" link color="transparent" @click="toForgotPassword">忘记密码</el-button>
            <el-divider direction="vertical" />
            <el-button link color="transparent" @click="toRegister">注册</el-button>
          </div>
        </el-form>
      </div>
      <div v-else class="form_box">
        <el-form class="custom_form" ref="formRef" :model="forgotPasswordForm" :rules="rules" size="large">
          <el-form-item prop="phone">
            <el-input v-model="forgotPasswordForm.phone" type="text" placeholder="请输入手机号" clearable></el-input>
          </el-form-item>
          <el-form-item prop="smsCode">
            <div class="code_box">
              <el-input v-model="forgotPasswordForm.smsCode" placeholder="手机验证码" clearable></el-input>
              <el-button :disabled="smsCodeDisabled" color="#409EFF" @click="doSendSmsCode">{{ smsCodeText }}</el-button>
            </div>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="forgotPasswordForm.password" type="password" placeholder="请输入密码" clearable></el-input>
          </el-form-item>
          <el-form-item prop="password1">
            <el-input v-model="forgotPasswordForm.password1" type="password" placeholder="请再次输入新密码" clearable></el-input>
          </el-form-item>
          <div class="other">
            <el-button class="btns" @click="toLoginForm">返回</el-button>
            <el-button class="btns" color="#409EFF" @click="doUpdataPassword">提交</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="login">
  import { getTokenApi, getImgCodeApi, sendSmsCodeApi } from '@/api/api'
  import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
  import { useStore } from 'vuex' 

  const currentThis = getCurrentInstance().appContext.config.globalProperties

  const store = useStore()
  window.localStorage.clear()
  window.sessionStorage.clear()
  store.commit('accessToken', '')
  store.commit('refreshToken', '')
  
  const currentData = reactive({
    loading: false,
    show: true,
    smsCodeDisabled: false,
    active: '2',
    smsCodeText: '获取验证码',
    verifyCodeImg: '',
    timer: '',
    form: {
      grant_type: 'captcha',
      username: '',
      password: '',
      phone: '',
      uuid: '',
      verifyCode: '',
      smsCode: ''
    },
    forgotPasswordForm: {
      phone: '',
      smsCode: '',
      password: '',
      password1: ''
    },
    rules: {
      username: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error(`请输入${currentData.active === '1' ? '手机号' : '账号'}`))
            } else {
              callback()
            }
          } 
        }
      ],
      phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
      password1: [{ required: true, message: '请再次输入新密码', trigger: 'blur' }],
      smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
      verifyCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
    }
  })
  let {loading, show, smsCodeDisabled, active, smsCodeText, verifyCodeImg, form, forgotPasswordForm, rules} = toRefs(currentData)

  // 通过ref获取dom
  const formRef = ref(null)

  function doLogin() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentData.loading = true
        let formData = new FormData()
        for (const key in currentData.form) {
          if(currentData.form[key]) {
            if(key === 'password') {
              formData.append(key, currentThis.$md5(currentData.form[key]))
            } else {
              formData.append(key, currentData.form[key])
            }
          }
        }
        getTokenApi(formData).then(res => {
          currentData.loading = false
          if(res.code === '200') {
            window.localStorage.setItem('accessToken', res.data.access_token)
            window.localStorage.setItem('refreshToken', res.data.refresh_token)
            store.commit('accessToken', res.data.access_token)
            store.commit('refreshToken', res.data.refresh_token)
            currentThis.$router.push({name: 'index'})
          } else {
            currentThis.$message.error(res.message)
            doGetImgCode()
          }
        }).catch(err => {
          currentData.loading = false
          doGetImgCode()
        })
      } else {
        return false;
      }
    })
  }

  // 发送手机验证码
  function doSendSmsCode() {
    if(!currentData.form.phone) {
      currentThis.$message.error('请输入手机号')
      return
    }
    sendSmsCodeApi({phone: currentData.form.phone}).then(res => {
      if(res.code === '200') {
        let time = 120
        currentData.smsCodeDisabled = true
        currentData.smsCodeText = `${time}S重新获取`
        currentData.timer = setInterval(() => {
          if(time === 1) {
            resetSmsCodeBtn()
          } else {
            time--
            currentData.smsCodeText = `${time}S重新获取`
          }
        }, 1000)
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 获取图片验证码
  doGetImgCode()
  function doGetImgCode() {
    getImgCodeApi().then(res => {
      if(res.code === '200') {
        currentData.form.uuid = res.data.verifyCodeId
        currentData.verifyCodeImg = res.data.verifyCodeImg
      }
    })
  }

  // 跳转注册页面
  function toRegister() {
    currentThis.$router.push({name: 'register'})
  }

  // 切换到登录表单
  function toLoginForm() {
    if(currentData.timer) {
      resetSmsCodeBtn()
    }
    currentData.show = true
  }

  // 忘记密码
  function toForgotPassword() {
    if(currentData.timer) {
      resetSmsCodeBtn()
    }
    currentData.show = false
  }

  // 修改密码
  function doUpdataPassword() {
    formRef.value.validate((valid) => {
      if (valid) {
      } else {
        return false;
      }
    })
  }

  // 重置登录表单
  function resetForm() {
    currentData.form = { 
      grant_type: currentData.active === '1' ? 'sms_code': 'captcha',
      username: '',
      password: '',
      phone: '',
      uuid: '',
      verifyCode: '',
      smsCode: ''
    }
    formRef.value.resetFields()
    if(currentData.timer) {
      resetSmsCodeBtn()
    }
    if(currentData.active === '2') {
      doGetImgCode()
    }
  }

  // 重置发送短信验证码按钮属性
  function resetSmsCodeBtn() {
    currentData.smsCodeDisabled = false
    currentData.smsCodeText = '获取验证码'
    clearInterval(currentData.timer)
  }
</script>

<style lang="less" scoped>
.login{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-image: url('@/assets/bg.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .login_form{
    width: 22%;
    border-radius: 10px;
    :deep(.el-tabs__nav){
      justify-content: space-around;
      float: none;
      .el-tabs__item{
        color: #ffffff;
      }
      .is-active{
        color: #409EFF !important;
      }
    }
    .title{
      width: 100%;
      color: #3F9DFD;
      font-size: 30px;
      font-weight: 500;
      text-align: center;
      margin-bottom: 10px;
    }
    .form_box{
      padding: 20px 50px 30px;
      background: rgba(64,158,255,.25);
      border-radius: 10px;
      .custom_form{
        :deep(.el-form-item){
          margin-top: 10px;
          .el-input{
            .el-input__wrapper{
              box-shadow: none;
            }
          }
          .code_box{
            width: 100%;
            display: flex;
            justify-content: space-between;
            >.el-input{
              width: 62%;
            }
            >.el-button{
              width: 34%;
              color: #ffffff;
            }
            >.el-image{
              width: 34%;
              border-radius: 4px;
              cursor: pointer;
              .load-code{
                width: 100%;
                border-radius: 4px;
                text-align: center;
                background: #F5F7FA;
                color: #a8a8a8;
              }
            }
          }
        }
        .login_btn{
          width: 100%;
          font-size: 14px;
          letter-spacing: 5px;
          margin: 0 0 20px;
          color: #ffffff;
        }
        .other{
          display: flex;
          justify-content: center;
          align-items: center;
          .el-divider--vertical{
            height: 0.7em;
            border-left: 1px #c2c1c1 solid
          }
          .btns{
            width: 80%;
            font-size: 14px;
            letter-spacing: 2px;
            &:last-child{
              color: #ffffff;
            }
          }
        }
      }
    }
  }
}
</style>